// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export  class net extends cc.Component {

    get(url, callback, failback) {
        var xhr = cc.loader.getXMLHttpRequest();
        console.log("Status: Send Get Request to " + url);
        xhr.open("GET", url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {  
                if(xhr.status >= 200 && xhr.status <= 207){
                    callback(xhr.responseText); 
                }else{
                    cc.log("请求超时",xhr.status)
                    failback(xhr.responseText);
                }
            }
        };
        xhr.timeout = 5000;// 5 seconds for timeout
        xhr.send();
    }

    /**
     * post请求
     * @param {string} url 
     * @param {object} params 选填
     * @param {function} callback 
     */
    post(url, params, callback, failback) {
        var nums = arguments.length  
        if(nums == 2){  
            callback = arguments[1];  
            params = "";  
        }  
        var xhr = cc.loader.getXMLHttpRequest();  
        xhr.open("POST", url);  
        xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");  
        xhr.onreadystatechange = function () {  
            if (xhr.readyState === 4) {  
                if(xhr.status >= 200 && xhr.status <= 207){
                    callback(xhr.responseText); 
                }else{
                    failback(xhr.responseText);
                }
            }
        };
        xhr.timeout = 5000;// 5 seconds for timeout
        xhr.send(params); 
    }
}
